<?php

namespace App\Exports;

use App\Models\Qh_Question;
use App\Models\Qh_QuestionType;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;

class QhQuestionExport implements FromCollection
{
    protected array $params;
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
    * @return Collection
    */
    public function collection(): Collection
    {
        return new Collection($this->createData());
    }

    public function createData(): array
    {
        $questions = Qh_Question::whereIn('id', $this->params['ids'])->get();
        $collect = [
            ['题目', '题型', '选项A', '选项B', '选项C', '选项D', '答案', '解析']
        ];

        foreach ($questions as $question) {
            $questionTypeName = Qh_QuestionType::find($question->questionTypeId)->value('name') ?? '';
            $options = explode('|NTK|', $question->options);

            foreach ($options as &$option) {
                if (mb_substr($option, 0, 2) == 'A、' || mb_substr($option, 0, 2) == 'B、' || mb_substr($option, 0, 2) == 'C、' || mb_substr($option, 0, 2) == 'D、') {
                    $option = mb_substr($option, 2);
                }
            }

            $collect[] = [
                $question->title,
                $questionTypeName,
                !empty($options[0]) ? $options[0] : null,
                !empty($options[1]) ? $options[1] : null,
                !empty($options[2]) ? $options[2] : null,
                !empty($options[3]) ? $options[3] : null,
                $question->answer,
                $question->analysis,
            ];
        }

        return $collect;
    }
}
